<template>
  <div :class="`box-content min-h-30px w-full flex flex-row flex-wrap`" ref="containerRef">

    
        <!-- 分类横向滚动 -->
        <div class="category-tabs">
      <div
        v-for="cat in categoryList"
        :key="cat.id"
        :class="['category-tab', { active: cat.id === categoryId }]"

        :style="cat.id === categoryId
          ? {
              color: property.categoryBtn.actColor,
              fontWeight: property.categoryBtn.weight ? 'bold' : 'normal',
              fontSize: property.categoryBtn.fontSize + 'rpx',
              background: property.categoryBtn.bgBeginColor,
              borderBottom: property.categoryBtn.underlineColor ? `2px solid ${property.categoryBtn.underlineColor}` : '2px solid transparent'
            }
          : {
              color: property.categoryBtn.color,
              borderBottom: '2px solid transparent',
              background: property.categoryBtn.bgColor,
              fontSize: property.categoryBtn.fontSize + 'rpx',
              fontWeight: 'normal'
            }"
        @click="onCategoryChange(cat.id)"
      >
        {{ cat.name }}
      </div>
    </div>

    <div
      class="relative box-content flex flex-row flex-wrap overflow-hidden bg-white"
      :style="{
        ...calculateSpace(index),
        ...calculateWidth(),
        borderTopLeftRadius: `${property.borderRadiusTop}px`,
        borderTopRightRadius: `${property.borderRadiusTop}px`,
        borderBottomLeftRadius: `${property.borderRadiusBottom}px`,
        borderBottomRightRadius: `${property.borderRadiusBottom}px`
      }"
      v-for="(article, index) in articleList"
      :key="index"
    >
      <!-- 角标 -->
      <div v-if="property.badge.show" class="absolute left-0 top-0 z-1 items-center justify-center">
        <el-image fit="cover" :src="property.badge.imgUrl" class="h-26px w-38px" />
      </div>
      <!-- 文章封面图 -->
      <div
        :class="[
          'h-140px',
          {
            'w-full': property.layoutType !== 'oneColSmallImg',
            'w-140px': property.layoutType === 'oneColSmallImg'
          }
        ]"
      >
        <el-image fit="cover" class="h-full w-full" :src="article.picUrl" />
      </div>
      <div
        :class="[
          ' flex flex-col gap-8px p-8px box-border',
          {
            'w-full': property.layoutType !== 'oneColSmallImg',
            'w-[calc(100%-140px-16px)]': property.layoutType === 'oneColSmallImg'
          }
        ]"
      >
        <!-- 文章标题 -->
        <div
          v-if="property.fields.title.show"
          :class="[
            'text-14px ',
            {
              truncate: property.layoutType !== 'oneColSmallImg',
              'overflow-ellipsis line-clamp-2': property.layoutType === 'oneColSmallImg'
            }
          ]"
          :style="{ color: property.fields.title.color }"
        >
          {{ article.title }}
        </div>
        <!-- 文章作者 -->
        <div
          v-if="property.fields.author.show"
          class="text-12px"
          :style="{ color: property.fields.author.color }"
        >
          {{ article.author }}
        </div>
        <!-- 文章简介 -->
        <div
          v-if="property.fields.introduction.show"
          class="truncate text-12px"
          :style="{ color: property.fields.introduction.color }"
        >
          {{ article.introduction }}
        </div>
        <!-- 浏览量 -->
        <div
          v-if="property.fields.browseCount.show"
          class="text-12px"
          :style="{ color: property.fields.browseCount.color }"
        >
          浏览 {{ article.browseCount }}
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { CategoryArticleCardProperty } from './config'
import * as ArticleApi from '@/api/mall/promotion/article'
import * as ArticleCategoryApi from '@/api/mall/promotion/articleCategory'

/** 分类文章卡片 */
defineOptions({ name: 'CategoryArticleCard' })
// 定义属性
const props = defineProps<{ property: CategoryArticleCardProperty }>()
// 文章列表
const articleList = ref<ArticleApi.ArticleVO[]>([])
watch(
  () => props.property.articleIds,
  async () => {
    const articles = await Promise.all(
      props.property.articleIds.map(id => ArticleApi.getArticle(id))
    )
    articleList.value = articles
  },
  {
    immediate: true,
    deep: true
  }
)

const categoryList = ref<ArticleCategoryApi.ArticleCategoryVO[]>([])
const categoryId = ref(0)

const fetchCategoryList = async () => {
  
  if(props.property.categoryIds){
    const categories = await Promise.all(props.property.categoryIds.map(id => ArticleCategoryApi.getArticleCategory(id)))
    categoryList.value = categories

    if (categoryList.value.length > 0) {
    onCategoryChange(categoryList.value[0].id)
  }
  }
  
}

const onCategoryChange = async (id: number) => {
  categoryId.value = id
  const articles = await ArticleApi.getArticlePage({
    categoryId: id,
    pageNo: 1,
    pageSize: 10
  })
  articleList.value = articles.list
}

// 监听分类ID变化
watch(
  () => props.property.categoryIds,
  async (newIds) => {
    if (newIds.length > 0) {
      //根据ID查询分类并拼接到categoryList
      const categories = await Promise.all(newIds.map(id => ArticleCategoryApi.getArticleCategory(id)))
      categoryList.value = categories
      if (categoryList.value.length > 0 ) {
        onCategoryChange(categoryList.value[0].id)
      }
    }else{
      categoryList.value = []
    }
  },
  {
    immediate: true,
    deep: true
  }
)

/**
 * 计算文章的间距
 * @param index 文章索引
 */
const calculateSpace = (index: number) => {
  // 文章的列数
  const columns = props.property.layoutType === 'twoCol' ? 2 : 1
  // 第一列没有左边距
  const marginLeft = index % columns === 0 ? '0' : props.property.space + 'px'
  // 第一行没有上边距
  const marginTop = index < columns ? '0' : props.property.space + 'px'

  return { marginLeft, marginTop }
}



// 容器
const containerRef = ref()
// 计算文章的宽度
const calculateWidth = () => {
  let width = '100%'
  // 双列时每列的宽度为：（总宽度 - 间距）/ 2
  if (props.property.layoutType === 'twoCol') {
    width = `${(containerRef.value.offsetWidth - props.property.space) / 2}px`
  }
  return { width }
}

onMounted(async () => {
  
  await fetchCategoryList()
})
</script>

<style scoped lang="scss">
.category-tabs {
  display: flex;
  min-width: 100%;
  margin-bottom: 12px;
  overflow-x: auto;
  white-space: nowrap;
  background-color: black;
}

.category-tab {
  min-width: 143px;
  padding: 8px 16px;
  margin-right: 8px;
  text-align: center;
  cursor: pointer;
  user-select: none;
  flex-shrink: 0;
}
</style>

